package org.github.xhjcehust.dubbo.proxy.controller;

import cn.htd.basecenter.dto.AddressInfo;
import cn.htd.basecenter.service.BaseAddressService;
import cn.htd.center.business.purchase.dto.PurchaseDTO;
import cn.htd.center.business.purchase.service.PurchaseApi;
import cn.htd.center.business.user.service.UserApi;
import cn.htd.center.central.member.dto.*;
import cn.htd.center.central.member.service.*;
import cn.htd.center.central.user.dto.CusCustomerDTO;
import cn.htd.center.central.user.dto.CusUserDTO;
import cn.htd.center.central.user.service.CusCustomerService;
import cn.htd.center.central.user.service.CusUserService;
import cn.htd.common.dao.util.RedisDB;
import cn.htd.common.middleware.MiddlewareInterfaceUtil;
import cn.htd.framework.common.BasePager;
import cn.htd.framework.common.BaseRequestParam;
import cn.htd.framework.common.DataGrid;
import cn.htd.framework.common.ExecuteResult;
import cn.htd.membercenter.common.constant.ErpStatusEnum;
import cn.htd.membercenter.common.constant.GlobalConstant;
import cn.htd.membercenter.common.constant.StaticProperty;
import cn.htd.membercenter.common.util.DESUtil;
import cn.htd.membercenter.common.util.Md5Utils;
import cn.htd.membercenter.dto.YijifuCorporateCallBackDTO;
import cn.htd.membercenter.dto.YijifuCorporateDTO;
import cn.htd.membercenter.dto.YijifuCorporateModifyDTO;
import cn.htd.membercenter.dto.*;
import cn.htd.membercenter.service.MemberBaseInfoService;
import cn.htd.membercenter.service.MemberBaseService;
import cn.htd.membercenter.service.MemberGradeService;
import cn.htd.membercenter.service.PayInfoService;
import cn.htd.messagecenter.service.SensitiveWordService;
import cn.htd.secretcenter.service.SecretForDesService;
import cn.htd.usercenter.dto.UserDTO;
import cn.htd.usercenter.service.UserExportService;
import cn.htd.zeus.tc.api.OrderQueryAPI;
import cn.htd.zeus.tc.dto.OuterOrderDTO;
import cn.htd.zeus.tc.dto.response.OuterOrderImportResponseDTO;
import cn.htd.zeus.tc.dto.resquest.OuterOrderImportRequestDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.github.xhjcehust.dubbo.proxy.data.WeakPwdCheckList;
import org.github.xhjcehust.dubbo.proxy.util.ExcelData;
import org.github.xhjcehust.dubbo.proxy.util.FileUtil;
import org.github.xhjcehust.dubbo.proxy.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
public class HTDController {

    private Logger logger = LoggerFactory.getLogger(HTDController.class);

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private SecretForDesService secretForDesService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private MemberBaseInfoService memberBaseInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private MemberBaseService memberBaseService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusUserService cusUserService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusMemberBaseInfoService cusMemberBaseInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusMemberCompanyInfoService cusMemberCompanyInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusMemberInvoiceInfoService cusMemberInvoiceInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusCustomerService customerService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private MemberGradeService memberGradeService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusBuyerGradeInfoService cusBuyerGradeInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private UserExportService userExportService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusMyMemberService cusMyMemberService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusMemberLicenceInfoService cusMemberLicenceInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}",timeout=60000)
    private CusMemberStatusInfoService cusMemberStatusInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusVerifyInfoService cusVerifyInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private PayInfoService payInfoService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusBoxRelationshipService cusBoxRelationshipService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusMemberCompanyPictureService cusMemberCompanyPictureService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private OrderQueryAPI orderQueryAPI;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private PurchaseApi purchaseApi;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private UserApi userApi;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private SensitiveWordService sensitiveWordService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusBelongRelationshipService cusBelongRelationshipService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private CusBusinessRelationshipService cusBusinessRelationshipService;

    @Reference(version="${dubbo.registry.version}",registry = "${dubbo.registry.address}")
    private BaseAddressService baseAddressService;

    @Autowired
    private JedisPool jedis;


    @RequestMapping("/importSMMembersByExcel")
    public String importSMMembersByExcel(){

        try{
            ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\数美会员数据导入.xlsx", "Sheet1");
            List<MemberBaseInfoRegisterDTO> list = sheet1.readSMExcelData();

            for(MemberBaseInfoRegisterDTO dto : list){
                System.out.println("开始："+JSONObject.toJSONString(dto));
                cn.htd.common.ExecuteResult<String> insertResult = memberBaseInfoService.insertMemberBaseRegisterInfo(dto);
                if(!insertResult.isSuccess()){
                    throw new RuntimeException(JSONObject.toJSONString(insertResult.getErrorMessages()));
                }
                System.out.println("结束："+insertResult.getResult());
            }
            return "ok";
        }catch (Exception e){
            return e.getMessage();
        }
    }

    @RequestMapping("/batchEncrypt")
    public String batchEncrypt(){

        try{
            ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\批量加密手机号.xlsx", "Sheet1");
            List<MemberBaseInfoRegisterDTO> list = sheet1.readJMExcelData();

            List<String> resList = new ArrayList<>();
            for(MemberBaseInfoRegisterDTO dto : list){
                String res = secretForDesService.encrypt(dto.getBusinessPersonMobile(),"","");
                String sql = "update member_company_info set business_person_mobile='"+res+"',modify_time=now() where member_id = "+dto.getMemberId()+";";
                resList.add(sql);
            }
            System.out.println("-----------------------------------------");
            for(String sql : resList){
                System.out.println(sql);
            }
            System.out.println("-----------------------------------------");
            return "ok";
        }catch (Exception e){
            return e.getMessage();
        }
    }

    @RequestMapping("/resolveStorePosition")
    public String resolveStorePosition(){
        try{
            ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\无storePosition列表.xlsx", "Sheet1");
            List<MemberBaseInfoRegisterDTO> list = sheet1.readNoStorePositionExcelData();

            List<String> resList = new ArrayList<>();
            for(MemberBaseInfoRegisterDTO dto : list){

                String locationDetail = secretForDesService.encrypt(dto.getLocationDetail(),"","");
                dto.setLocationDetail(locationDetail);

                String locationTown = memberBaseService.getAddressBaseByCode(dto.getLocationTown());
                dto.setLocationTown(locationTown);

                String locationCounty = memberBaseService.getAddressBaseByCode(dto.getLocationCounty());
                dto.setLocationCounty(locationCounty);

                if (StringUtils.contains(dto.getLocationTown(), "乡")
                        || StringUtils.contains(dto.getLocationTown(), "镇")
                        || (!StringUtils.contains(dto.getLocationCounty(), "区")
                        && (StringUtils.contains(dto.getLocationDetail(), "村")
                        || StringUtils.contains(dto.getLocationDetail(), "屯")))) {
                    dto.setStorePosition("乡镇店");
                } else {
                    dto.setStorePosition("城郊店");
                }

                String sql = "update member_company_info set store_position='"+dto.getStorePosition()+"',modify_time=now() where member_id = "+dto.getMemberId()+";";
                resList.add(sql);
            }
            System.out.println("-----------------------------------------");
            for(String sql : resList){
                System.out.println(sql);
            }
            System.out.println("-----------------------------------------");
            return "ok";
        }catch (Exception e){
            return e.getMessage();
        }
    }


    @RequestMapping("/resolveUserMobile")
    public String resolveUserMobile(){
        try{
            ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\member.xlsx", "Sheet1");
            List<String> list = sheet1.readMemberCodes();

//            String str = "htd20279965";
//            String str = "htd23132674,htd40170558,htd23132561,07010019,07010021,htd20132343";
//            List<String> list = Arrays.asList(str.split(","));

            int count = 0;
            int size = list.size();
            for(String item : list){
                System.out.println("-----------------------------");
                ExecuteResult<CusUserDTO> userDTOExecuteResult = cusUserService.queryUserByLoginId(item);
                String mobile = userDTOExecuteResult.getResult().getMobile();
                Long id = userDTOExecuteResult.getResult().getId();
                System.out.println("id:"+id+" mobile:"+mobile);
                if(id==null||StringUtils.isEmpty(mobile)){
                    throw new RuntimeException("userid或mobile为空1："+JSONObject.toJSONString(userDTOExecuteResult));
                }

                String res3 = secretForDesService.decrypt(mobile,"","");
                System.out.println(res3);
                if(StringUtils.isEmpty(res3)){
                    count++;
                    System.out.println("总数："+size+" 已完成："+count);
                    continue;
                }

                CusUserDTO dto = new CusUserDTO();
                dto.setId(id);
                dto.setPassword(Md5Utils.getMd5(res3));
                dto.setMobile(res3);
                dto.setLastUpdateId(id);
                ExecuteResult<Boolean> update = cusUserService.updateCusUserById(dto);
                count++;
                System.out.println(update);
                System.out.println("总数："+size+" 已完成："+count);
                System.out.println("-----------------------------");
            }
            return "ok";
        }catch (Exception e){
            return e.getMessage();
        }
    }

    @RequestMapping("/resolveMemberAddress")
    public String resolveMemberAddress(){
        try{

//            String target = "actualBusinessAddress";
//            String target = "actualBusinessDetail";
            String target = "locationAddr";
//            String target = "locationDetail";

            String str = "440,442,444,537,628,1839,3899,13988,16196,16307,16575,16790,16907,17144,18001,18057,19013,19542,19543,19830,21126,23737,24376,25340,25691,26048,26127,27030,27731,28070,30405,30521,35942,40338,44119,56579,62760,63751,64713,68731,69510,72565,74847,74927,83208,84603,84917,92765,95947,102533,109555,122167,124891,142353,145173,145175,147581,148747,149537,149781,149795,156453,158461,159549,166043,182469,182855,182937,182943,184157,184257,198827,211679,223295,224327,224821,230387,231769,254227,259521,268277,269153,274819,282387,284717,307185,320421,320473,321991,322453,325383,340347,342985,347613,354333,354477,356629,360833,361377,362539,363321,364003,364761";
//            String str = "1,2,3,5,6,7,8,9,10";
            List<String> list = Arrays.asList(str.split(","));


            int count = 0;
            int size = list.size();
            for(String item : list){
                System.out.println("-----------------------------");

                CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
                cusMemberBaseInfoDTO.setBuyerSellerType("1");
                cusMemberBaseInfoDTO.setId(Long.valueOf(item));

                ExecuteResult<CusMemberBaseInfoDTO> selectResult = cusMemberBaseInfoService.selectMemberBaseInfo(cusMemberBaseInfoDTO);
                if(!selectResult.isSuccess()){
                    throw new RuntimeException("address为空："+JSONObject.toJSONString(selectResult.getErrorMessages()));
                }
                String address = null;
                switch (target){
                    case "actualBusinessAddress":
                        address = selectResult.getResult().getActualBusinessAddress();
                        break;
                    case "actualBusinessDetail":
                        address = selectResult.getResult().getActualBusinessDetail();
                        break;
                    case "locationAddr":
                        address = selectResult.getResult().getLocationAddr();
                        break;
                    case "locationDetail":
                        address = selectResult.getResult().getLocationDetail();
                        break;
                }

                String decryptStr = secretForDesService.decrypt(address,"","");
                //如果解密出来没有值说明该数据可以加密
                if(StringUtils.isEmpty(decryptStr)){
                    address = secretForDesService.encrypt(address,"","");
                    if(StringUtils.isEmpty(item)||StringUtils.isEmpty(address)){
                        throw new RuntimeException("id或者address为空："+JSONObject.toJSONString(selectResult.getErrorMessages()));
                    }

                    CusMemberCompanyInfoDTO cusMemberCompanyInfoDTO = new CusMemberCompanyInfoDTO();
                    cusMemberCompanyInfoDTO.setModifyTime(new Date());
                    switch (target){
                        case "actualBusinessAddress":
                            cusMemberCompanyInfoDTO.setActualBusinessAddress(address);
                            break;
                        case "actualBusinessDetail":
                            cusMemberCompanyInfoDTO.setActualBusinessDetail(address);
                            break;
                        case "locationAddr":
                            cusMemberCompanyInfoDTO.setLocationAddr(address);
                            break;
                        case "locationDetail":
                            cusMemberCompanyInfoDTO.setLocationDetail(address);
                            break;
                    }
                    CusMemberCompanyInfoDTO filterDTO = new CusMemberCompanyInfoDTO();
                    filterDTO.setMemberId(Long.valueOf(item));

                    ExecuteResult<Boolean> updateResult = cusMemberCompanyInfoService.updateCusMemberCompanyInfoByParam(cusMemberCompanyInfoDTO,filterDTO);
                    if(!updateResult.isSuccess()){
                        throw new RuntimeException("更新失败："+JSONObject.toJSONString(updateResult.getErrorMessages()));
                    }
                }
                count++;
                System.out.println("总数："+size+" 已完成："+count);
                System.out.println("-----------------------------");
            }
            return "ok";
        }catch (Exception e){
            return e.getMessage();
        }
    }

    @RequestMapping("/qcc")
    public String qcc(String companyName){
        String APPKEY  = "7dd1b172f91941d7a88cc45e675303d2";
        String SECRETKEY  = "D7F921325D6C954D508219AFD63C0C08";

        String url="http://api.qichacha.com/ECIV4/GetBasicDetailsByName?key="+APPKEY+"&dtype=json&keyword="+companyName;
        StringBuilder json = new StringBuilder();
        try {
            URL getUrl = new URL(url);
            // 返回URLConnection子类的对象
            HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
            String timestamp = String.valueOf((System.currentTimeMillis()/1000));//精确到秒的Unix时间戳
            String token = Md5Utils.getMd5(APPKEY + timestamp + SECRETKEY);    //验证加密值
            connection.setRequestProperty("Timespan",timestamp);
            connection.setRequestProperty("Token", token.toUpperCase());  //设置请求的token
            // 连接
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            // 使用Reader读取输入流
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String lines;
            while ((lines = reader.readLine()) != null) {
                json.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (Exception e) {
	        e.printStackTrace();
        }
        return json.toString();
    }

    @RequestMapping("/noMemberCanLogin")
    public String noMemberCanLogin(String memberCode){
        List<CusMemberBaseInfoDTO> selectList = null;
        if (StringUtils.isEmpty(memberCode)){
            //读excel
            ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\非会员名单.xlsx", "Sheet1");
            selectList = sheet1.readNoMember();
        }else{
            selectList = new ArrayList<>();
            CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
            cusMemberBaseInfoDTO.setMemberCode(memberCode);
            cusMemberBaseInfoDTO.setBuyerSellerType("1");
            ExecuteResult<CusMemberBaseInfoDTO> singleRs = cusMemberBaseInfoService.selectMemberBaseInfo(cusMemberBaseInfoDTO);
            if (!singleRs.isSuccess()){
                throw new RuntimeException(singleRs.getErrorMessages().toString());
            }
            selectList.add(singleRs.getResult());
        }

        //无效memberCode
        List<String> inValid = new ArrayList<>();
        //错误对象
        Map<String,Object> error = new HashMap();
        int count = 0;
        for(int i=0,l=selectList.size();i<l;i++){
            CusMemberBaseInfoDTO dto = selectList.get(i);
            if(!dto.getCompanyName().contains("测试")&&!dto.getCompanyName().contains("test")&&!dto.getCompanyName().contains("终止")){
                //插入user和customer表
                cn.htd.common.ExecuteResult<UserDTO> userResult = userExportService.queryUserByLoginId(dto.getMemberCode());
                if(!userResult.isSuccess()){
                    throw new RuntimeException(userResult.getErrorMessages().toString());
                }
                if(userResult.getResult()==null){
                    CusUserDTO cusUserDTO = new CusUserDTO();
                    cusUserDTO.setName(dto.getCompanyName());
                    cusUserDTO.setLoginId(dto.getMemberCode());
                    cusUserDTO.setMobile(dto.getBusinessPersonMobile());
                    if (StringUtils.isNotEmpty(dto.getBusinessPersonMobile())){
                        cusUserDTO.setPassword(Md5Utils.getMd5(dto.getBusinessPersonMobile()));
                    }else{
                        cusUserDTO.setPassword(Md5Utils.getMd5("123456"));
                    }
                    cusUserDTO.setEmail("");
                    cusUserDTO.setCreateId(0L);
                    cusUserDTO.setLastUpdateId(0L);
                    cusUserDTO.setDataTag(dto.getDataTag());
                    cusUserDTO.setMemberId(dto.getId());
                    cusUserDTO.setMemberCode(dto.getMemberCode());
                    CusUserDTO insertUserResult = cusUserService.insertUser(cusUserDTO);
                    if(insertUserResult!=null){
                        CusCustomerDTO customerDTO = new CusCustomerDTO();
                        customerDTO.setUserId(insertUserResult.getId());
                        customerDTO.setCompanyId(dto.getId());
                        customerDTO.setIsVmsInnerUser(0);
                        customerDTO.setDefaultContact(1);
                        customerDTO.setCreatedId(0L);
                        customerDTO.setDeletedFlag(0);
                        customerDTO.setLastUpdatedId(0L);
                        customerDTO.setDataTag(dto.getDataTag());
                        customerService.addCustomer(customerDTO);
                    }
                }
                //更新canMallLogin
//                Date updateDate = new Date();
//                CusMemberBaseInfoDTO updateParam = new CusMemberBaseInfoDTO();
//                updateParam.setId(dto.getId());
//                updateParam.setCanMallLogin(1);
//                updateParam.setModifyTime(updateDate);
//                ExecuteResult<Boolean> updateResult = cusMemberBaseInfoService.updateCusMemberBaseInfoById(updateParam);
//                if(!updateResult.isSuccess()){
//                    error.put("cusMemberBaseInfoService.updateCusMemberBaseInfoById",dto);
//                    throw new RuntimeException(updateResult.getErrorMessages().toString());
//                }
                ExecuteResult<CusBuyerGradeInfoDTO> selectGradeResult = cusBuyerGradeInfoService.selectCusBuyerGradeInfoById(dto.getId());
                if(!selectGradeResult.isSuccess()){
                    error.put("cusBuyerGradeInfoService.selectCusBuyerGradeInfoById",dto);
                    throw new RuntimeException(selectGradeResult.getErrorMessages().toString());
                }
                if(selectGradeResult.getResult()==null){
                    //插入buyer_grade_info表
                    BuyerGradeInfoDTO gradeDto = new BuyerGradeInfoDTO();
                    gradeDto.setBuyerId(dto.getId());
                    gradeDto.setBuyerGrade("1");
                    gradeDto.setPointGrade(1L);
                    gradeDto.setCreateId(0L);
                    gradeDto.setCreateName("sys");
                    gradeDto.setModifyId(0L);
                    gradeDto.setModifyName("sys");
                    cn.htd.common.ExecuteResult<Boolean> booleanGradeResult = memberGradeService.insertGrade(gradeDto);
                    if(!booleanGradeResult.isSuccess()){
                        error.put("memberGradeService.insertGrade",dto);
                        throw new RuntimeException(booleanGradeResult.getErrorMessages().toString());
                    }
                }
            }else{
                inValid.add(dto.getCompanyName());
            }

            System.out.println("总共"+selectList.size()+"，已完成"+(++count)+"，"+dto.getMemberCode());
        }

        error.put("inValid",inValid);

        return JSONObject.toJSONString(error);
    }

    /**
     * insert into member_extend_info
     * @return
     */
    @RequestMapping("/saveNoMemberExtendOperating")
    public String saveNoMemberExtendOperating(){
        CusMyNoMemberDTO dto = new CusMyNoMemberDTO();
        dto.setMemberId(94265L);
        dto.setCustomerName("安徽省文胜生物工程股份有限公司");
        dto.setOperatingMobile("15956852034");
        dto.setOperatingName("李文胜");
        dto.setIndustryCategory("5");
        dto.setModifyId(0L);
        dto.setModifyName("sys");
        dto.setOperatingIdcard("");
        dto.setOperatingPicSrc("");
        dto.setOperatingPicBackSrc("");
        dto.setOperatingIdcardPicSrc("");
        ExecuteResult<Integer> insert = cusMyMemberService.saveNoMemberExtendOperating(dto);
        return JSONObject.toJSONString(insert.getResult());
    }


    /**
     * insert into member_licence_info
     * @return
     */
    @RequestMapping("/insertCusMemberLicenceInfo")
    public String insertCusMemberLicenceInfo(){
        CusMemberLicenceInfoDTO dto = new CusMemberLicenceInfoDTO();
        dto.setMemberId(224537L);
        dto.setBuyerBusinessLicenseId("eo59hDUKF0cEPRM_-a9z5118QYRD_u5c");
        dto.setBusinessLicenseId("eo59hDUKF0cEPRM_-a9z5118QYRD_u5c");
        dto.setUnifiedSocialCreditCode("eo59hDUKF0cEPRM_-a9z5118QYRD_u5c");
        dto.setBuyerBusinessLicensePicSrc("/20210526/cZnh3sfFhN.jpg");
        dto.setBusinessLicensePicSrc("/20210526/cZnh3sfFhN.jpg");
        dto.setCertificateType("2");
        dto.setTaxpayerType("1");
        dto.setCreateId(0L);
        dto.setCreateName("sys");
        dto.setModifyId(0L);
        dto.setModifyName("sys");
        ExecuteResult<CusMemberLicenceInfoDTO> insert = cusMemberLicenceInfoService.insertCusMemberLicenceInfo(dto);
        return JSONObject.toJSONString(insert.getResult());
    }

    /**
     * insert into box_relationship
     * @return
     */
    @RequestMapping("/insertCusBoxRelationship")
    public String insertCusBoxRelationship(){
        CusBoxRelationshipDTO cusMemberBusinessRelationDTO = new CusBoxRelationshipDTO();
        cusMemberBusinessRelationDTO.setBuyerId(524L);
        cusMemberBusinessRelationDTO.setSellerId(519L);
        cusMemberBusinessRelationDTO.setErpStatus("1");
        cusMemberBusinessRelationDTO.setAuditStatus("1");
        cusMemberBusinessRelationDTO.setCreateId(0L);
        cusMemberBusinessRelationDTO.setCompanyName("sys");
        cusMemberBusinessRelationDTO.setModifyId(0L);
        cusMemberBusinessRelationDTO.setModifyName("sys");
        ExecuteResult<CusBoxRelationshipDTO> result = cusBoxRelationshipService.insertCusBoxRelationship(cusMemberBusinessRelationDTO);
        return JSONObject.toJSONString(result.getResult());
    }

    /**
     * insert into box_relationship
     * @return
     */
    @RequestMapping("/checkAInsertCusBoxRelationship")
    public String checkAInsertCusBoxRelationship(){
        String[] ids = "".split(",");
        for (String id : ids){

            ExecuteResult<CusApplyBusiRelationDTO> countResult =
                    cusBoxRelationshipService.queryBoxRelationInfoByMemberIdAndSellerId(Long.valueOf(id),487347L);
            if (!countResult.isSuccess()){
                continue;
            }

            if (countResult.getResult() == null){
                CusBoxRelationshipDTO cusMemberBusinessRelationDTO = new CusBoxRelationshipDTO();
                cusMemberBusinessRelationDTO.setBuyerId(Long.valueOf(id));
                cusMemberBusinessRelationDTO.setSellerId(487347L);
                cusMemberBusinessRelationDTO.setErpStatus("1");
                cusMemberBusinessRelationDTO.setAuditStatus("");
                cusMemberBusinessRelationDTO.setCreateId(0L);
                cusMemberBusinessRelationDTO.setCompanyName("sys");
                cusMemberBusinessRelationDTO.setModifyId(0L);
                cusMemberBusinessRelationDTO.setModifyName("sys");
                ExecuteResult<CusBoxRelationshipDTO> result = cusBoxRelationshipService.insertCusBoxRelationship(cusMemberBusinessRelationDTO);
                logger.info(JSONObject.toJSONString(result.getResult()));
            }else {
                logger.info("已存在记录：{}",id);
            }
        }
        return "200";
    }

    /**
     * 补充支付账号
     * @return
     */
    @RequestMapping("/updateAccountNo")
    public String updateAccountNo(){
        String [] idStr = "469467,477893".split(",");
        List<Long> ids = new ArrayList<>();
        for(String id : idStr){
            ids.add(Long.valueOf(id));
        }
        CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
        cusMemberBaseInfoDTO.setIds(ids);
        cusMemberBaseInfoDTO.setBuyerSellerType("1");
        ExecuteResult<List<CusMemberBaseInfoDTO>> memberListResult =
                cusMemberBaseInfoService.selectMemberBaseInfoListNoSecret(cusMemberBaseInfoDTO);
        if (!memberListResult.isSuccess()){
            throw new RuntimeException(memberListResult.getErrorMessages().toString());
        }
        List<CusMemberBaseInfoDTO> list = memberListResult.getResult();
        for (int i=0,l=list.size();i<l;i++ ){
            CusMemberBaseInfoDTO dto = list.get(i);
            YijifuCorporateDTO yijifuDto = new YijifuCorporateDTO();
            yijifuDto.setOutUserId(dto.getMemberCode());
            yijifuDto.setCorporateUserType("BUSINESS");
            yijifuDto.setComName(dto.getCompanyName());

            LegalPerson legalPerson = new LegalPerson();
            String address = dto.getLocationAddr();
            if (StringUtils.isNotEmpty(address)){
                address = secretForDesService.decrypt(address,"","");
                legalPerson.setAddress(address);
            }
            String certNo = dto.getArtificialPersonIdcard();
            if (StringUtils.isNotEmpty(certNo)){
                certNo = secretForDesService.decrypt(certNo,"","");
                legalPerson.setCertNo(certNo);
            }
            String mobile = dto.getArtificialPersonMobile();
            if (StringUtils.isNotEmpty(mobile)){
                mobile = secretForDesService.decrypt(mobile,"","");
                legalPerson.setMobileNo(mobile);
            }
            legalPerson.setRealName(dto.getArtificialPersonName());
            yijifuDto.setLegalPerson(legalPerson);

            cn.htd.common.ExecuteResult<YijifuCorporateCallBackDTO> yijifuCallbackDtoResult = payInfoService.realNameSaveVerify(yijifuDto);
            if(!yijifuCallbackDtoResult.isSuccess()){
                System.err.println("易极付异常 memberId:"+dto.getId()+" error:"+yijifuCallbackDtoResult.getErrorMessages());
                continue;
            }
            String accountNo = yijifuCallbackDtoResult.getResult().getAccountNo();
            if (StringUtils.isEmpty(accountNo)){
                System.err.println("未生成支付账号 memberId:"+dto.getId()+" 原因:"+yijifuCallbackDtoResult.getResult().getResultDetail());
                continue;
            }
            CusMemberCompanyInfoDTO updateParam = new CusMemberCompanyInfoDTO();
            updateParam.setAccountNo(accountNo);
            updateParam.setModifyTime(new Date());
            CusMemberCompanyInfoDTO filterParam = new CusMemberCompanyInfoDTO();
            filterParam.setMemberId(dto.getId());
            ExecuteResult<Boolean> updateResult = cusMemberCompanyInfoService.updateCusMemberCompanyInfoByParam(updateParam,filterParam);
            if (!updateResult.isSuccess()){
                System.err.println("修改异常 memberId:"+dto.getId()+" accountNo:"+accountNo+" error:"+updateResult.getErrorMessages());
                throw new RuntimeException(updateResult.getErrorMessages().toString());
            }

            System.out.println("总共："+list.size()+"，已完成:"+(i+1)+"，memberId:"+dto.getId()+" accountNo:"+accountNo);
        }

        return "ok";
    }

    /**
     * 补充支付账号
     * @return
     */
    @RequestMapping("/updateAccountNoByExcel")
    public String updateAccountNoByExcel(){
        ExcelData sheet1 = new ExcelData("C:\\Users\\大糊\\Desktop\\补充支付账号.xlsx", "Sheet1");
        List<CusMemberBaseInfoDTO> list = sheet1.readAccountNo();
        for (CusMemberBaseInfoDTO dto : list){
            CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
            cusMemberBaseInfoDTO.setMemberCode(dto.getMemberCode());
            cusMemberBaseInfoDTO.setBuyerSellerType("1");
            ExecuteResult<List<CusMemberBaseInfoDTO>> listExecuteResult =
                    cusMemberBaseInfoService.selectMemberBaseInfoListNoSecret(cusMemberBaseInfoDTO);
            if (listExecuteResult.getResult()!=null && listExecuteResult.getResult().size()>0){
                CusMemberBaseInfoDTO exist = listExecuteResult.getResult().get(0);

                YijifuCorporateDTO yijifuDto = new YijifuCorporateDTO();
                yijifuDto.setOutUserId(exist.getMemberCode());
                yijifuDto.setCorporateUserType("BUSINESS");
                yijifuDto.setComName(exist.getCompanyName());
                LegalPerson legalPerson = new LegalPerson();
                legalPerson.setRealName(dto.getArtificialPersonName());
                yijifuDto.setLegalPerson(legalPerson);
                cn.htd.common.ExecuteResult<YijifuCorporateCallBackDTO> yijifuCallbackDtoResult = payInfoService.realNameSaveVerify(yijifuDto);
                if(!yijifuCallbackDtoResult.isSuccess()){
                    System.err.println("易极付异常 memberId:"+exist.getId()+" error:"+yijifuCallbackDtoResult.getErrorMessages());
                    continue;
                }
                String accountNo = yijifuCallbackDtoResult.getResult().getAccountNo();
                if (StringUtils.isEmpty(accountNo)){
                    System.err.println("未生成支付账号 memberId:"+exist.getId()+" 原因:"+yijifuCallbackDtoResult.getResult().getResultDetail());
                    continue;
                }
                CusMemberCompanyInfoDTO updateParam = new CusMemberCompanyInfoDTO();
                String province = getAddressCode(dto.getLocationProvince(),1,null);
                String city = getAddressCode(dto.getLocationCity(),2,province);
                String county = getAddressCode(dto.getLocationCounty(),3,city);
                String town = getAddressCode(dto.getLocationTown(),4,county);
                if (StringUtils.isEmpty(province)||StringUtils.isEmpty(city)||StringUtils.isEmpty(county)||StringUtils.isEmpty(town)){
                    System.err.println("地址编码不正确"+exist.getId());
                    continue;
                }
                updateParam.setLocationProvince(province);
                updateParam.setLocationCity(city);
                updateParam.setLocationCounty(county);
                updateParam.setLocationTown(town);
                updateParam.setActualBusinessProvince(province);
                updateParam.setActualBusinessCity(city);
                updateParam.setActualBusinessCounty(county);
                updateParam.setActualBusinessTown(town);

                String locationDetail = secretForDesService.encrypt(dto.getLocationDetail(),"","");
                String locationAddr = secretForDesService.encrypt(dto.getLocationAddr(),"","");
                updateParam.setLocationDetail(locationDetail);
                updateParam.setLocationAddr(locationAddr);
                updateParam.setActualBusinessDetail(locationDetail);
                updateParam.setActualBusinessAddress(locationAddr);
                updateParam.setAccountNo(accountNo);
                updateParam.setArtificialPersonName(dto.getArtificialPersonName());
                updateParam.setModifyTime(new Date());
                CusMemberCompanyInfoDTO filterParam = new CusMemberCompanyInfoDTO();
                filterParam.setMemberId(exist.getId());
                ExecuteResult<Boolean> updateResult = cusMemberCompanyInfoService.updateCusMemberCompanyInfoByParam(updateParam,filterParam);
                if (!updateResult.isSuccess()){
                    System.err.println("修改公司异常 memberId:"+exist.getId()+" accountNo:"+accountNo+" error:"+updateResult.getErrorMessages());
                    throw new RuntimeException(updateResult.getErrorMessages().toString());
                }

                CusMemberInvoiceInfoDTO updateInvoParam = new CusMemberInvoiceInfoDTO();
                updateInvoParam.setMemberId(exist.getId());
                updateInvoParam.setInvoiceNotify(exist.getCompanyName());
                updateInvoParam.setInvoiceCompanyName(exist.getCompanyName());
                updateInvoParam.setModifyTime(new Date());
                CusMemberInvoiceInfoDTO filterInvo = new CusMemberInvoiceInfoDTO();
                filterInvo.setMemberId(exist.getId());
                ExecuteResult<Boolean> updateInvoice = cusMemberInvoiceInfoService.updateCusMemberInvoiceInfoByParam(updateInvoParam,filterInvo);
                if (!updateInvoice.isSuccess()){
                    System.err.println("修改发票异常 memberId:"+exist.getId()+" error:"+updateInvoice.getErrorMessages());
                    throw new RuntimeException(updateResult.getErrorMessages().toString());
                }

                CusMemberBaseInfoDTO updateBase = new CusMemberBaseInfoDTO();
                updateBase.setId(exist.getId());
                updateBase.setModifyTime(new Date());
                cusMemberBaseInfoService.updateCusMemberBaseInfoById(updateBase);
            }

        }
        return "ok";
    }

    private String getAddressCode(String name,Integer level,String parent){
        List<AddressInfo> list = baseAddressService.getAddressListByName(name,level);
        if (list!=null && list.size()>0){
            String code = null;
            for (AddressInfo info : list){
                if (level == 1 || (parent!=null && info.getCode().contains(parent))){
                    code = info.getCode();
                    break;
                }
            }
            return code;
        }
        return null;
    }

    /**
     * 更新公司信息
     * @return
     */
    @RequestMapping("/updateCompanyInfo")
    public String updateCompanyInfo() throws ParseException {

        ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\修改公司信息模板.xlsx", "Sheet1");
        List<CusMemberOutsideSupplierCompanyDTO> list = sheet1.readCompanyInfo();
        List<String> memberCodes = list.stream().map(CusMemberOutsideSupplierCompanyDTO::getMemberCode).collect(Collectors.toList());
        CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
        cusMemberBaseInfoDTO.setBuyerSellerType("1");
        cusMemberBaseInfoDTO.setMemberCodes(memberCodes);
        ExecuteResult<List<CusMemberBaseInfoDTO>> listExecuteResult =
                cusMemberBaseInfoService.selectMemberBaseInfoListNoSecret(cusMemberBaseInfoDTO);
        if (!listExecuteResult.isSuccess()){
            throw new RuntimeException(listExecuteResult.getErrorMessages().toString());
        }
        List<CusMemberBaseInfoDTO> memberList = listExecuteResult.getResult();
        for (CusMemberBaseInfoDTO member : memberList){
            for (CusMemberOutsideSupplierCompanyDTO company : list){
                if (company.getMemberCode().equals(member.getMemberCode())){

                    CusMemberCompanyInfoDTO cusMemberCompanyInfoDTO = new CusMemberCompanyInfoDTO();
                    cusMemberCompanyInfoDTO.setId(member.getCompanyId());
                    cusMemberCompanyInfoDTO.setBusinessPersonMobile(secretForDesService.encrypt(company.getBusinessPersonMobile(),"",""));
                    cusMemberCompanyInfoDTO.setArtificialPersonMobile(secretForDesService.encrypt(company.getArtificialPersonMobile(),"",""));
                    cusMemberCompanyInfoDTO.setLocationAddr(secretForDesService.encrypt(company.getLocationAddr(),"",""));
                    cusMemberCompanyInfoDTO.setActualBusinessAddress(secretForDesService.encrypt(company.getActualBusinessAddress(),"",""));
                    cusMemberCompanyInfoDTO.setLocationDetail(secretForDesService.encrypt(company.getLocationDetail(),"",""));
                    cusMemberCompanyInfoDTO.setActualBusinessDetail(secretForDesService.encrypt(company.getActualBusinessDetail(),"",""));
                    cusMemberCompanyInfoDTO.setModifyTime(new Date());

                    //更新易极付
                    if (StringUtils.isNotEmpty(member.getAccountNo())){
                        YijifuCorporateModifyDTO yijifuDto = new YijifuCorporateModifyDTO();
                        yijifuDto.setUserId(member.getAccountNo());
                        if (StringUtils.isNotEmpty(company.getArtificialPersonMobile())) {
                            yijifuDto.setMobileNo(company.getArtificialPersonMobile());
                        }
                        if (StringUtils.isNotEmpty(company.getLocationAddr())) {
                            yijifuDto.setRegisterAddress(company.getLocationAddr());
                        }
                        cn.htd.common.ExecuteResult<YijifuCorporateCallBackDTO> yijifuCallbackDtoResult = payInfoService.realNameModifyVerify(yijifuDto);
                        if(!yijifuCallbackDtoResult.isSuccess()){
                            throw new RuntimeException(yijifuCallbackDtoResult.getErrorMessages().toString());
                        }
                    }else{
                        //更新易极付
                        YijifuCorporateDTO yijifuDto = new YijifuCorporateDTO();
                        yijifuDto.setOutUserId(member.getMemberCode());
                        yijifuDto.setCorporateUserType("BUSINESS");
                        yijifuDto.setComName(member.getCompanyName());

                        LegalPerson legalPerson = new LegalPerson();
                        String locationAddr = StringUtils.isEmpty(company.getLocationAddr())?member.getLocationAddr():company.getLocationAddr();
                        legalPerson.setAddress(locationAddr);
                        legalPerson.setCertNo(secretForDesService.decrypt(member.getArtificialPersonIdcard(),"",""));
                        String artificialPersonMobile = StringUtils.isEmpty(company.getArtificialPersonMobile())?member.getArtificialPersonMobile():company.getArtificialPersonMobile();
                        legalPerson.setMobileNo(artificialPersonMobile);
                        legalPerson.setRealName(member.getArtificialPersonName());
                        yijifuDto.setLegalPerson(legalPerson);

                        cn.htd.common.ExecuteResult<YijifuCorporateCallBackDTO> yijifuCallbackDtoResult = payInfoService.realNameSaveVerify(yijifuDto);
                        if(!yijifuCallbackDtoResult.isSuccess()){
                            throw new RuntimeException(yijifuCallbackDtoResult.getErrorMessages().toString());
                        }

                        cusMemberCompanyInfoDTO.setAccountNo(yijifuCallbackDtoResult.getResult().getAccountNo());
                    }

                    //下行erp
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date trancDate = format.parse(format.format(new Date()));
                    CusMemberStatusInfoDTO statusInfo = new CusMemberStatusInfoDTO();
                    statusInfo.setMemberId(member.getId());
                    statusInfo.setInfoType(GlobalConstant.INFO_TYPE_ERP_MODIFY);
                    statusInfo.setVerifyStatus(ErpStatusEnum.PENDING.getValue());
                    statusInfo.setSyncErrorMsg("");
                    statusInfo.setSyncKey("");
                    statusInfo.setModifyId(0L);
                    statusInfo.setModifyName("sys");
                    statusInfo.setModifyTime(trancDate);
                    statusInfo.setVerifyId(0L);
                    statusInfo.setVerifyTime(trancDate);
                    statusInfo.setCreateId(0L);
                    statusInfo.setCreateName("sys");
                    statusInfo.setCreateTime(trancDate);
                    cusVerifyInfoService.deleteMemberStatus(statusInfo);
                    cusVerifyInfoService.insertMemberStatus(statusInfo);

                    //更新member_company_info
                    if (cusMemberCompanyInfoDTO.getId()!=null){
                        ExecuteResult<Boolean> updateCompanyResult =
                                cusMemberCompanyInfoService.updateCusMemberCompanyInfoById(cusMemberCompanyInfoDTO);
                        if (!updateCompanyResult.isSuccess()){
                            throw new RuntimeException(updateCompanyResult.getErrorMessages().toString());
                        }
                    }

                    //更新时间
                    if(member.getId()!=null){
                        CusMemberBaseInfoDTO memberBaseInfoDTO = new CusMemberBaseInfoDTO();
                        memberBaseInfoDTO.setId(member.getId());
                        memberBaseInfoDTO.setModifyTime(new Date());
                        ExecuteResult<Boolean> updateBaseResult = cusMemberBaseInfoService.updateCusMemberBaseInfoById(memberBaseInfoDTO);
                        if (!updateBaseResult.isSuccess()){
                            throw new RuntimeException(updateBaseResult.getErrorMessages().toString());
                        }
                    }

                    //更新登录手机号
                    if (StringUtils.isNotEmpty(company.getBusinessPersonMobile())){
                        cn.htd.common.ExecuteResult<UserDTO> userResult =
                                userExportService.queryUserByLoginId(member.getMemberCode());
                        if (!userResult.isSuccess()){
                            UserDTO userDTO = userResult.getResult();
                            String mobile = secretForDesService.encrypt(company.getBusinessPersonMobile(),"","");
                            CusUserDTO cusUserDTO = new CusUserDTO();
                            cusUserDTO.setId(userDTO.getId());
                            cusUserDTO.setMobile(StringUtils.isNotEmpty(mobile)?mobile:userDTO.getMobile());
                            ExecuteResult<Boolean> updateMobileResult = cusUserService.updateCusUserById(cusUserDTO);
                            if (!updateMobileResult.isSuccess()){
                                throw new RuntimeException(updateMobileResult.getErrorMessages().toString());
                            }
                        }
                    }

                    logger.info("已更新记录：memberCode[{}],businessPersonMobile[{}],artificialPersonMobile[{}],locationAddr[{}]",
                            company.getMemberCode(),company.getBusinessPersonMobile(),company.getArtificialPersonMobile(),company.getLocationAddr());
                }
            }
        }
        return "";
    }

    /**
     * 更新companyPic异常照片
     * @return
     */
    @RequestMapping("/resolveCompanyPic")
    public String resolveCompanyPic(){
        //塞入memberId
        String memberIdStr = "248293,248292,248267";
        String [] memberIds = memberIdStr.split(",");
        List<Long> ids = new ArrayList<>();
        for (String id : memberIds){
            ids.add(Long.valueOf(id));
        }
        if (ids.isEmpty()){
            throw new RuntimeException("error");
        }
        CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
        cusMemberBaseInfoDTO.setIds(ids);
        ExecuteResult<List<CusMemberBaseInfoDTO>> memberResult =
                cusMemberBaseInfoService.selectMemberBaseInfoListNoSecret(cusMemberBaseInfoDTO);
        if (!memberResult.isSuccess()){
            throw new RuntimeException(memberResult.getErrorMessages().toString());
        }
        List<CusMemberBaseInfoDTO> list = memberResult.getResult();
        for (int i=0,l=list.size();i<l;i++){
            CusMemberBaseInfoDTO dto = list.get(i);
            Boolean storeInsideFlag = false;
            Boolean storeOutsideFlag = false;
            if(StringUtils.isNotEmpty(dto.getStoreInsidePicSrc())){
                List<CusMemberCompanyPictureDTO> picList = new ArrayList<>();
                CusMemberCompanyPictureDTO pictureDTO = new CusMemberCompanyPictureDTO();
                pictureDTO.setCompanyId(dto.getCompanyId());
                pictureDTO.setPictureUrl(dto.getStoreInsidePicSrc());
                pictureDTO.setPicType("1");
                pictureDTO.setCreateId(0L);
                pictureDTO.setCreateName("sys");
                picList.add(pictureDTO);
                if(picList.size()>0){
                    picList.get(0).setIsFirst(1);//选择第一个作为主图
                    cusMemberCompanyPictureService.deleteAndInsertCusMemberCompanyPicture(picList);
                    storeInsideFlag = true;
                }
            }
            //补充照片表信息（门头照）
            if(StringUtils.isNotEmpty(dto.getStoreOutsidePicSrc())){
                List<CusMemberCompanyPictureDTO> picList = new ArrayList<>();
                CusMemberCompanyPictureDTO pictureDTO = new CusMemberCompanyPictureDTO();
                pictureDTO.setCompanyId(dto.getCompanyId());
                pictureDTO.setPictureUrl(dto.getStoreOutsidePicSrc());
                pictureDTO.setPicType("2");
                pictureDTO.setCreateId(0L);
                pictureDTO.setCreateName("sys");
                picList.add(pictureDTO);
                if(picList.size()>0){
                    picList.get(0).setIsFirst(1);//选择第一个作为主图
                    cusMemberCompanyPictureService.deleteAndInsertCusMemberCompanyPicture(picList);
                    storeOutsideFlag = true;
                }
            }

            logger.info("总共:{},已完成:{},已更新记录：memberId[{}],全部更新[{}]",
                    l,(i+1),dto.getId(),(storeOutsideFlag&&storeInsideFlag)?"true":"false");
        }

        return "ok";
    }

    /**
     * 批量更新弱密码库
     * @return
     */
    @RequestMapping("/batchInsertWeekPwd")
    public String batchInsertWeekPwd(){
//        String [] pwd = "123456.com,123123,idc123!@#".split(",");
        String [] pwd = "".split(",");
        Pipeline pipeline = jedis.getResource().pipelined();
        for (String p : pwd){
            pipeline.hset("invalidPwd",p,"1");
        }
        List<Object> results = pipeline.syncAndReturnAll();
        return "ok";
    }

    /**
     * decrptExcel
     * @return
     */
    @RequestMapping("/decrptExcel")
    public String decrptExcel(){
        try{
            ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\member.xlsx", "member");
            List<MemberBaseInfoRegisterDTO> list = sheet1.decrptExcel();

            for(MemberBaseInfoRegisterDTO dto : list){
                if (StringUtils.isNotEmpty(dto.getTaxManId())){
                    String tmp = secretForDesService.decrypt(dto.getTaxManId(),"","");
                    dto.setTaxManId(StringUtils.isEmpty(tmp)?dto.getTaxManId():tmp);
                }
                if (StringUtils.isNotEmpty(dto.getContactPhone())){
                    String tmp = secretForDesService.decrypt(dto.getContactPhone(),"","");
                    dto.setContactPhone(StringUtils.isEmpty(tmp)?dto.getContactPhone():tmp);
                }
                if (StringUtils.isNotEmpty(dto.getInvoiceAddress())){
                    String tmp = secretForDesService.decrypt(dto.getInvoiceAddress(),"","");
                    dto.setInvoiceAddress(StringUtils.isEmpty(tmp)?dto.getInvoiceAddress():tmp);
                }
                if (StringUtils.isNotEmpty(dto.getBankAccount())){
                    String tmp = secretForDesService.decrypt(dto.getBankAccount(),"","");
                    dto.setBankAccount(StringUtils.isEmpty(tmp)?dto.getBankAccount():tmp);
                }

                System.out.println(dto.getMemberCode()+","+dto.getCompanyName()+","+dto.getTaxManId()+","+dto.getContactPhone()+","+dto.getInvoiceAddress()+","+dto.getBankName()+","+dto.getBankAccount());
            }
            return "ok";
        }catch (Exception e){
            return e.getMessage();
        }
    }

    /**
     * 批量更新外部订单
     * @return
     */
    @RequestMapping("/batchUpdateOutOrder")
    public String batchUpdateOutOrder(){
        ExcelData sheet1 = new ExcelData("C:\\Users\\08011707\\Desktop\\test1.xlsx", "Sheet1");
        List<OuterOrderImportRequestDTO> list = sheet1.readOutOrder();
        long start = System.currentTimeMillis();
        cn.htd.common.ExecuteResult<OuterOrderImportResponseDTO> result = orderQueryAPI.batchUpdateOuterOrderInfo(list);
        System.out.println("耗时:"+(System.currentTimeMillis()-start));
        return JSONObject.toJSONString(result);
    }

    /**
     * 校验弱密码名单
     * @return
     */
    @RequestMapping("/checkWeakPwdList")
    public String checkWeakPwdList(){
        //弱密码库
        Map<String, String> weakcenterMap = jedis.getResource().hgetAll("invalidPwd");
        List<String> weakcenterList = new ArrayList<>();
        for (Map.Entry<String,String> entry : weakcenterMap.entrySet()){
            weakcenterList.add(Md5Utils.getMd5(entry.getKey()));
        }
        System.out.println("弱密码库准备完成");
        //数字密码
        for (int i=0;i<999999;i++){
            weakcenterList.add(Md5Utils.getMd5(i+""));
        }
        System.out.println("数字密码准备完成");

        List<CusUserDTO> failList = new ArrayList<>();
        List<List<String>> loginPages = new ArrayList<>();
        List<String> loginIdList = new ArrayList<>();
        AtomicInteger count = new AtomicInteger();
        for(int i = 0, l = WeakPwdCheckList.loginIds.length; i<l; i++){
            loginIdList.add(WeakPwdCheckList.loginIds[i]);
            if (loginIdList.size()==100){//定量更新
                loginPages.add(loginIdList);
                loginIdList = new ArrayList<>();
            }
        }
        if (CollectionUtils.isNotEmpty(loginIdList)){//更新剩余
            loginPages.add(loginIdList);
        }

        ExecutorService executorService = Executors.newFixedThreadPool(20);
        CountDownLatch cdl = new CountDownLatch(WeakPwdCheckList.loginIds.length);
        for (List<String> list : loginPages){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    CusUserDTO cusUserDTO = new CusUserDTO();
                    cusUserDTO.setLoginIds(list);
                    ExecuteResult<List<CusUserDTO>> listExecuteResult = cusUserService.selectCusUserList(cusUserDTO);
                    for (CusUserDTO dto : listExecuteResult.getResult()){
                        String mobileEncr = secretForDesService.decrypt(dto.getMobile(),"","");
                        String mobile = Md5Utils.getMd5(StringUtils.isNotEmpty(mobileEncr)?mobileEncr:dto.getMobile());
                        if (weakcenterList.contains(dto.getPassword())||weakcenterList.contains(mobile)||dto.getPassword().equals(mobile)){
                            failList.add(dto);
                            System.out.println("发现弱密码："+dto.getLoginId()+","+dto.getName());
                        }
//                        count.incrementAndGet();
//                        System.out.println("总共："+WeakPwdCheckList.loginIds.length+" index："+(count.intValue()));
                        cdl.countDown();
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return JSONObject.toJSONString(failList);
    }

    /**
     * 升级采购商
     * @return
     */
    @RequestMapping("/upgradePurchase")
    public String upgradePurchase(){
        String result = null;
        BaseRequestParam<cn.htd.center.business.user.dto.MemberBaseInfoDTO> requestParam = new BaseRequestParam<>();
        cn.htd.center.business.user.dto.MemberBaseInfoDTO memberBaseInfoDTO = new cn.htd.center.business.user.dto.MemberBaseInfoDTO();
        memberBaseInfoDTO.setMemberCode("htd386421");
        memberBaseInfoDTO.setBuyerSellerType("1");
        requestParam.setBusinessBody(memberBaseInfoDTO);
        ExecuteResult<PurchaseDTO> selectResult = purchaseApi.selectPurchaseSeller(requestParam);
        if (selectResult.getResult()!=null){
            BaseRequestParam<PurchaseDTO> requestParam1 = new BaseRequestParam<>();
            PurchaseDTO purchaseDTO = selectResult.getResult();
            purchaseDTO.setModifyId(0L);
            purchaseDTO.setModifyName("sys");
            purchaseDTO.setMemberId(selectResult.getResult().getMemberBaseInfoDTO().getId());
            purchaseDTO.setMemberCode(selectResult.getResult().getMemberBaseInfoDTO().getMemberCode());
            requestParam1.setBusinessBody(purchaseDTO);
            ExecuteResult<Long> createResult = purchaseApi.createPurchaseSeller(requestParam1);
            result = JSONObject.toJSONString(createResult);
        }
        return result;
    }

    /**
     * 当前区域是否有经理人
     * @return
     */
    @RequestMapping("/isSuperManagerExist")
    public String isSuperManagerExist() throws Exception {
        String city = "2306";
        Map<String, String> requestParam = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("cityCode", city); //城市编码
        requestParam.put("appParam",
                DESUtil.parseByte2HexStr(DESUtil.encrypt(JSON.toJSONString(map), DESUtil.key).getBytes()));
        requestParam.put("platform", "third");
        String url = StaticProperty.SUPERMANAGERURL4QRYBRANCHAUDITORBYCITY;
        logger.info("加密参数:{}", DESUtil.parseByte2HexStr(DESUtil.encrypt(JSON.toJSONString(map), DESUtil.key).getBytes()));
        logger.info("访问经理人url={}, 参数：{}", url, JSON.toJSONString(map));
        String requestResult = MiddlewareInterfaceUtil.httpPost(url, requestParam, Boolean.FALSE);
        logger.info("访问经理人结果:{}", new String(
                DESUtil.decrypt(new String(DESUtil.parseHexStr2Byte(requestResult)), DESUtil.key).getBytes(),
                "UTF-8"));
        return requestResult;
    }

    /**
     * 处理终止的营业执照号
     * @return
     */
    @RequestMapping("/teminateBuyerBusinessLicenceId")
    public String teminateBuyerBusinessLicenceId() throws Exception {
        Integer index = 0;
        CusMemberStatusInfoDTO cusMemberStatusInfoDTO = new CusMemberStatusInfoDTO();
        cusMemberStatusInfoDTO.setInfoType("11");
        cusMemberStatusInfoDTO.setVerifyStatus("4");
        ExecuteResult<List<CusMemberStatusInfoDTO>> listExecuteResult =
                cusMemberStatusInfoService.selectCusMemberStatusInfoList(cusMemberStatusInfoDTO);
        if (!listExecuteResult.isSuccess()){
            throw new RuntimeException(listExecuteResult.getErrorMessages().toString());
        }
        List<CusMemberStatusInfoDTO> list = listExecuteResult.getResult();
        for (CusMemberStatusInfoDTO cusStatus : list){
            index++;
            CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
            cusMemberBaseInfoDTO.setId(cusStatus.getMemberId());
            cusMemberBaseInfoDTO.setBuyerSellerType("1");
            ExecuteResult<CusMemberBaseInfoDTO> memberLicenceInfoResult =
                    cusMemberBaseInfoService.selectMemberBaseInfoLicence(cusMemberBaseInfoDTO);
            if (memberLicenceInfoResult.isSuccess()&&memberLicenceInfoResult.getResult()!=null){
                CusMemberBaseInfoDTO licenceInfoDTO = memberLicenceInfoResult.getResult();
                if (StringUtils.isEmpty(licenceInfoDTO.getBuyerBusinessLicenseId())){
                    logger.info("终止3：{},进度：{}",cusStatus.getMemberId(),index+"/"+list.size());
                }else{
                    boolean updateFlag = false;
                    String buyerBusinessLicenseId = licenceInfoDTO.getUnifiedSocialCreditCode()+"终止";
                    CusMemberLicenceInfoDTO cusMemberLicenceInfoDTO = new CusMemberLicenceInfoDTO();
                    cusMemberLicenceInfoDTO.setMemberId(cusStatus.getMemberId());
                    if (StringUtils.isNotEmpty(licenceInfoDTO.getBuyerBusinessLicenseId()) &&
                            !licenceInfoDTO.getBuyerBusinessLicenseId().contains("终止")){
                        cusMemberLicenceInfoDTO.setBuyerBusinessLicenseId(buyerBusinessLicenseId);
                        updateFlag = true;
                    }
                    if (StringUtils.isNotEmpty(licenceInfoDTO.getUnifiedSocialCreditCode()) &&
                            !licenceInfoDTO.getUnifiedSocialCreditCode().contains("终止")){
                        cusMemberLicenceInfoDTO.setUnifiedSocialCreditCode(buyerBusinessLicenseId);
                        updateFlag = true;
                    }
                    if (StringUtils.isNotEmpty(licenceInfoDTO.getBusinessLicenseId()) &&
                            !licenceInfoDTO.getBusinessLicenseId().contains("终止")){
                        cusMemberLicenceInfoDTO.setBusinessLicenseId(buyerBusinessLicenseId);
                        updateFlag = true;
                    }
//                    if (StringUtils.isNotEmpty(licenceInfoDTO.getTaxManId()) &&
//                            !licenceInfoDTO.getTaxManId().contains("终止")){
//                        cusMemberLicenceInfoDTO.setTaxManId(buyerBusinessLicenseId);
//                    }
                    if (updateFlag){
                        cn.htd.framework.common.ExecuteResult<Boolean> updateLicenceResult =
                                cusMemberLicenceInfoService.updateCusMemberLicenceInfoByMemberId(cusMemberLicenceInfoDTO);
                        if (!updateLicenceResult.isSuccess()){
                            throw new RuntimeException(updateLicenceResult.getErrorMessages().toString());
                        }
                        logger.info("终止1：{},{},进度：{}",cusStatus.getMemberId(),licenceInfoDTO.getBuyerBusinessLicenseId(),index+"/"+list.size());
                    } else{
                        logger.info("终止2：{},{},进度：{}",cusStatus.getMemberId(),licenceInfoDTO.getBuyerBusinessLicenseId(),index+"/"+list.size());
                    }
                }
            }else{
                logger.info("不存在的数据：{},进度：{}",cusStatus.getMemberId(),index+"/"+list.size());
            }
        }
        return "200";
    }

    /**
     * 新增敏感词
     * @return
     */
    @RequestMapping("/insertSensitive")
    public String insertSensitive() {
        String [] word = "严重逾期".split(",");
        cn.htd.common.ExecuteResult<Integer> requestResult =
                sensitiveWordService.insertSensitiveWord(Arrays.asList(word));
        return JSONObject.toJSONString(requestResult);
    }

    /**
     * 刷新敏感词
     * @return
     */
    @RequestMapping("/refreshSensitive")
    public String refreshSensitive() {
        cn.htd.common.ExecuteResult<Boolean> requestResult =
                sensitiveWordService.refreshSensitiveWord();
        return JSONObject.toJSONString(requestResult);
    }

//    /**
//     * 终止会员
//     * @return
//     */
//    @RequestMapping("/terminationMember")
//    public String terminationMember() {
//        CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
//        cusMemberBaseInfoDTO.setMemberCode("htd20391564");
//        cusMemberBaseInfoDTO.setBuyerSellerType("1");
//        ExecuteResult<CusMemberBaseInfoDTO> memberResult = cusMemberBaseInfoService.selectMemberBaseInfoLicence(cusMemberBaseInfoDTO);
//        Long memberId = memberResult.getResult().getId();
//        Date d = new Date();
//        if (memberResult.getResult()!=null){
//            String buyerBusinessLicenceId = memberResult.getResult().getBuyerBusinessLicenseId();
//            if (StringUtils.isNotEmpty(buyerBusinessLicenceId)){
//                buyerBusinessLicenceId += "终止";
//                CusMemberLicenceInfoDTO cusMemberLicenceInfoDTO = new CusMemberLicenceInfoDTO();
//                cusMemberLicenceInfoDTO.setMemberId(memberId);
//                cusMemberLicenceInfoDTO.setBuyerBusinessLicenseId(buyerBusinessLicenceId);
//                cusMemberLicenceInfoDTO.setBusinessLicenseId(buyerBusinessLicenceId);
//                cusMemberLicenceInfoDTO.setUnifiedSocialCreditCode(buyerBusinessLicenceId);
//                cusMemberLicenceInfoDTO.setTaxManId(buyerBusinessLicenceId);
//                ExecuteResult<Boolean> updateLicence = cusMemberLicenceInfoService.updateCusMemberLicenceInfoByMemberId(cusMemberLicenceInfoDTO);
//                if (!updateLicence.isSuccess()){
//                    throw new RuntimeException(updateLicence.getErrorMessages().toString());
//                }
//            }
//
//            String companyName = memberResult.getResult().getCompanyName()+"终止";
//            String businessPersonMobile = memberResult.getResult().getBusinessPersonMobile()+"终止";
//            CusMemberCompanyInfoDTO companyParam = new CusMemberCompanyInfoDTO();
//            companyParam.setCompanyName(companyName);
//            companyParam.setBusinessPersonMobile(businessPersonMobile);
//            companyParam.setModifyTime(d);
//            CusMemberCompanyInfoDTO companyFilter = new CusMemberCompanyInfoDTO();
//            companyFilter.setMemberId(memberId);
//            ExecuteResult<Boolean> updateCompany = cusMemberCompanyInfoService.updateCusMemberCompanyInfoByParam(companyParam,companyFilter);
//            if (!updateCompany.isSuccess()){
//                throw new RuntimeException(updateCompany.getErrorMessages().toString());
//            }
//
//            CusUserDTO cusUserDTO = new CusUserDTO();
//            cusUserDTO.setLoginId(memberResult.getResult().getMemberCode());
//            cusUserDTO.setName(companyName);
//            cusUserDTO.setMobile(businessPersonMobile);
//            ExecuteResult<Integer> updateUser = cusUserService.updateSingleUser(cusUserDTO);
//            if (!updateUser.isSuccess()){
//                throw new RuntimeException(updateUser.getErrorMessages().toString());
//            }
//
//            //修改下行
//            CusMemberStatusInfoDTO cusMemberStatusParam = new CusMemberStatusInfoDTO();// 会员审核状态信息
//            cusMemberStatusParam.setMemberId(memberId);
//            cusMemberStatusParam.setSyncKey("");
//            cusMemberStatusParam.setSyncErrorMsg("");
//            cusMemberStatusParam.setVerifyStatus(GlobalConstant.VERIFY_STATUS_WAIT);
//            cusMemberStatusParam.setInfoType(GlobalConstant.INFO_TYPE_ERP_MODIFY);
//            cusMemberStatusParam.setVerifyId(0L);
//            cusMemberStatusParam.setCreateId(0L);
//            cusMemberStatusParam.setCreateName("sys");
//            cusMemberStatusParam.setCreateTime(d);
//            cusMemberStatusParam.setModifyId(0L);
//            cusMemberStatusParam.setModifyName("sys");
//            cusMemberStatusParam.setModifyTime(d);
//            cusMemberStatusParam.setVerifyTime(d);
//            cusVerifyInfoService.deleteMemberStatus(cusMemberStatusParam);
//            cusVerifyInfoService.insertMemberStatus(cusMemberStatusParam);
//
//
//            CusMemberBaseInfoDTO baseParam = new CusMemberBaseInfoDTO();
//            baseParam.setId(memberId);
//            baseParam.setStatus("0");
//            baseParam.setModifyTime(d);
//            ExecuteResult<Boolean> updateBase = cusMemberBaseInfoService.updateCusMemberBaseInfoById(baseParam);
//            if (!updateBase.isSuccess()){
//                throw new RuntimeException(updateBase.getErrorMessages().toString());
//            }
//        }
//        return "200";
//    }

    /**
     * 获取少于18位的社统编码
     * @return
     */
    @RequestMapping("/transferLicenceId")
    public String transferLicenceId() {
        List result = new ArrayList();
        String[] ids = "410".split(",");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (String id : ids){
            CusMemberBaseInfoDTO cusMemberLicenceInfoDTO = new CusMemberBaseInfoDTO();
            cusMemberLicenceInfoDTO.setId(Long.valueOf(id));
            cusMemberLicenceInfoDTO.setBuyerSellerType("1");
            ExecuteResult<CusMemberBaseInfoDTO> listExecuteResult =
                    cusMemberBaseInfoService.selectAllMemberBaseInfo(cusMemberLicenceInfoDTO);
            if (listExecuteResult.getResult()!=null){
                CusMemberBaseInfoDTO dto = listExecuteResult.getResult();
                String unifiedSocialCreditCode = dto.getUnifiedSocialCreditCode();
                if (StringUtils.isNotEmpty(unifiedSocialCreditCode)){
                    String memberFlag = "";
                    if (unifiedSocialCreditCode.length()<18){
                        switch (dto.getMemberFlag()){
                            case "1":
                                memberFlag = "非会员";
                                break;
                            case "2":
                                memberFlag = "产业会员";
                                break;
                            case "3":
                                memberFlag = "会员";
                                break;
                        }
                        String s = dto.getMemberCode()+","+dto.getCompanyName()+","+sdf.format(dto.getCreateTime())+","+memberFlag+","+dto.getSupplierCode()+","+dto.getUnifiedSocialCreditCode()+","+dto.getTaxManId();
                        result.add(s);
                        System.out.println(s);
                    }
                }
            }
        }

        return JSONObject.toJSONString(result);
    }

    @RequestMapping("/resolveFlowBug")
    public String resolveFlowBug(){
        Long curId = 0L;
        try {
            String [] ids = "486003,486007,486013,486015".split(",");
            for (String id : ids){
                curId = Long.valueOf(id);
                CusMemberBaseInfoDTO cusMemberBaseParam = new CusMemberBaseInfoDTO();
                cusMemberBaseParam.setId(Long.valueOf(id));
                cusMemberBaseParam.setBuyerSellerType("1");
                ExecuteResult<CusMemberBaseInfoDTO> memberResult =
                        cusMemberBaseInfoService.selectMemberBaseInfo(cusMemberBaseParam);
                if (!memberResult.isSuccess()){
                    continue;
                }
                CusMemberBaseInfoDTO oldDto = memberResult.getResult();

                // 校验经营地址是否有区域经理人
                boolean isSuperManagerExist = false;
                if(StringUtils.isNotEmpty(oldDto.getActualBusinessCity())){
                    Map<String, String> requestParam = new HashMap<>();
                    Map<String, Object> map = new HashMap<>();
                    map.put("cityCode", oldDto.getActualBusinessCity()); //城市编码
                    requestParam.put("appParam",
                                DESUtil.parseByte2HexStr(DESUtil.encrypt(JSON.toJSONString(map), DESUtil.key).getBytes()));
                    requestParam.put("platform", "third");
                    String url = "http://spm.htd.cn/hsm/organizationRegister/qryBranchAuditorByCity";
//                    logger.info("加密参数:{}", DESUtil.parseByte2HexStrxStr(DESUtil.encrypt(JSON.toJSONString(map), DESUtil.key).getBytes()));
//                    logger.info("访问经理人url={}, 参数：{}", url, JSON.toJSONString(map));
                    String requestResult = MiddlewareInterfaceUtil.httpPost(url, requestParam, Boolean.FALSE);
//                    logger.info("访问经理人结果:{}", new String(
//                            DESUtil.decrypt(new String(DESUtil.parseHexStr2Byte(requestResult)), DESUtil.key).getBytes(),
//                            "UTF-8"));
                    JSONObject jsonResult = JSONObject.parseObject(new String(
                            DESUtil.decrypt(new String(DESUtil.parseHexStr2Byte(requestResult)), DESUtil.key).getBytes(),
                            "UTF-8"));
                    if(jsonResult.containsKey("status")&&jsonResult.getInteger("status")==1){
                        Integer data = jsonResult.getInteger("data");
                        isSuperManagerExist = data==1?true:false;
                    }
                }

                oldDto.setModifyId(0L);
                oldDto.setModifyName("sys");
                //进入经理人审核流
                if(!oldDto.getRegistFrom().equals("12")//非铁军
                        && isSuperManagerExist){//该经营地址有区域经理人
                    saveVerifyInfo(oldDto,GlobalConstant.INFO_TYPE_VERIFY_BUSINESS);
                }else{
                    // 进入供应商审批流
                    if (517 != oldDto.getCurBelongSellerId().longValue()) {// 有归属
                        saveVerifyInfo(oldDto,GlobalConstant.INFO_TYPE_VERIFY_COOPERATE);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("resolveFlowBug异常: memberId{}",curId);
        }

        return "200";
    }

    @RequestMapping("/updateTime")
    public String updateTime(){
        String [] ids = "70545,70749,70988,70989,70990,70991,72502,72503,73142,73425,73427,73448,73989,74160,74877,75550,76068,76073,76075,76613,91049,126007,156875,181753,186345,219381,276379,277033,277053,277313,277373,277553,277977,278095,279857,279875,279917,279923,279925,281161,281173,301181,313451,315741,344495,354627,359485,367351,367359,367373,367375,367707,367727,367799,367885,376935,430527,456915,478881,485099,485283,485287,487901,489075,489079,489081,489083,489085,489091,489093,489095,489097,489099,489101,489103,489107,489111,489113,489117,489121,489123,489125,489129,489131,489133,489135,489139,489143,489145,489147,489149,489155,489157,489159,489161,489163,489167,489169,489173,489175,489177,489179,489185,489187,489191,489193,489195,489199,489201,489203,489207,489209,489211,489213,489215,489217,489219,489221,489225,489229,489233,489235,489237,489239,489241,489505,489567,489649,489651,489657,489659,489667,489693,489695,489697,489699".split(",");
        Date d = new Date();
        for (String id : ids){
            CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
            if (StringUtils.isNotEmpty(id)){
                cusMemberBaseInfoDTO.setId(Long.valueOf(id));
                cusMemberBaseInfoDTO.setModifyTime(d);
                ExecuteResult<Boolean> updateResult =
                        cusMemberBaseInfoService.updateCusMemberBaseInfoById(cusMemberBaseInfoDTO);
                if (!updateResult.isSuccess()){
                    continue;
                }
            }
        }

        return "200";
    }

    private void saveVerifyInfo(CusMemberBaseInfoDTO oldDto,String infoType) throws ParseException {
        Date d = new Date();
        //保存审核信息
        CusVerifyInfoDTO verufyInfo = new CusVerifyInfoDTO();
        verufyInfo.setModifyType(infoType);
        verufyInfo.setRecordType("1");
        verufyInfo.setRemark("");
        verufyInfo.setVerifierId(0L);
        verufyInfo.setVerifierName("sys");
        verufyInfo.setRecordId(oldDto.getId());
        verufyInfo.setVerifyStatus(GlobalConstant.VERIFY_STATUS_WAIT);
        verufyInfo.setCreateId(0L);
        verufyInfo.setCreateName("sys");
        verufyInfo.setModifyId(0L);
        verufyInfo.setModifyName("sys");
        verufyInfo.setBelongSellerId(oldDto.getBelongSellerId());
        verufyInfo.setVerifyTime(d);
        verufyInfo.setCreateTime(d);
        verufyInfo.setModifyTime(d);
        ExecuteResult<CusVerifyInfoDTO> verifyResult = cusVerifyInfoService.saveVerifyInfoForID(verufyInfo);
        if(!verifyResult.isSuccess()){
            throw new RuntimeException(verifyResult.getErrorMessages().toString());
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date defaultDate = format.parse("0000-00-00 00:00:00");
        CusMemberStatusInfoDTO statusInfoDTO = new CusMemberStatusInfoDTO();
        statusInfoDTO.setMemberId(oldDto.getId());
        statusInfoDTO.setVerifyId(verifyResult.getResult().getId());
        statusInfoDTO.setInfoType(infoType);
        statusInfoDTO.setVerifyStatus(verufyInfo.getVerifyStatus());
        statusInfoDTO.setCreateId(0L);
        statusInfoDTO.setCreateName("sys");
        statusInfoDTO.setCreateTime(d);
        statusInfoDTO.setModifyId(0L);
        statusInfoDTO.setModifyName("sys");
        statusInfoDTO.setModifyTime(d);
        statusInfoDTO.setVerifyTime(defaultDate);
        statusInfoDTO.setSyncKey("");
        statusInfoDTO.setSyncErrorMsg("");
        ExecuteResult<String> insertStatusResult = cusVerifyInfoService.insertMemberStatus(statusInfoDTO);
        if (!insertStatusResult.isSuccess()) {
            throw new RuntimeException(insertStatusResult.getErrorMessages().toString());
        }

        CusMemberStatusInfoDTO cusMemberStatusInfoDTO = new CusMemberStatusInfoDTO();
        cusMemberStatusInfoDTO.setMemberId(oldDto.getId());
        cusMemberStatusInfoDTO.setInfoType("5");
        ExecuteResult<Integer> statusCount = cusMemberStatusInfoService.selectCusMemberStatusInfoCount(cusMemberStatusInfoDTO);
        if (!statusCount.isSuccess()){
            throw new RuntimeException(statusCount.getErrorMessages().toString());
        }
        if (statusCount.getResult()==0){
            CusMemberStatusInfoRegisterDTO cusMemberStatusInfoRegisterDTO = new CusMemberStatusInfoRegisterDTO();
            cusMemberStatusInfoRegisterDTO.setMemberId(oldDto.getId());
            cusMemberStatusInfoRegisterDTO.setInfoType("5");
            cusMemberStatusInfoRegisterDTO.setCreateId(0L);
            cusMemberStatusInfoRegisterDTO.setCreateName("sys");
            cusMemberStatusInfoRegisterDTO.setVerifyId(0L);
            cn.htd.framework.common.ExecuteResult<Boolean> result3 = cusMemberStatusInfoService.insertMemberStatusInfoRegister(cusMemberStatusInfoRegisterDTO);
            if(!result3.isSuccess()) {
                throw new RuntimeException(result3.getErrorMessages().toString());
            }
        }else{
            logger.info("已存在此记录，memberId:{}",oldDto.getId());
        }

        CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
        cusMemberBaseInfoDTO.setId(oldDto.getId());
        cusMemberBaseInfoDTO.setModifyTime(d);
        ExecuteResult<Boolean> updateBase = cusMemberBaseInfoService.updateCusMemberBaseInfoById(cusMemberBaseInfoDTO);
        if (!updateBase.isSuccess()){
            throw new RuntimeException(updateBase.getErrorMessages().toString());
        }
    }


    @RequestMapping("/checkBusinessLicenceExist")
    public boolean checkBusinessLicenceExist(){
        String businessLicenseId = "91320102MA222AFA8N";
        Long memberId = 356459L;
        if (org.apache.commons.lang.StringUtils.isEmpty(businessLicenseId)){
            return false;
        }
        CusMemberLicenceInfoDTO memberLicenceCheckParam1 = new CusMemberLicenceInfoDTO();
        memberLicenceCheckParam1.setBuyerBusinessLicenseId(businessLicenseId);
        ExecuteResult<List<CusMemberLicenceInfoDTO>> licenceCountResult1 =
                cusMemberLicenceInfoService.selectCusMemberLicenceInfoList(memberLicenceCheckParam1);
        if (!licenceCountResult1.isSuccess()){
            throw new RuntimeException(licenceCountResult1.getErrorMessages().toString());
        }
        if (licenceCountResult1.getResult().size()>0){
            if (memberId!=null){
                List<CusMemberLicenceInfoDTO> list = licenceCountResult1.getResult();
                for (CusMemberLicenceInfoDTO cusMemberLicenceInfoDTO : list){
                    if (!cusMemberLicenceInfoDTO.getMemberId().equals(memberId)){
                        return true;
                    }
                }
            }else{
                return true;
            }
        }
        CusMemberLicenceInfoDTO memberLicenceCheckParam2 = new CusMemberLicenceInfoDTO();
        memberLicenceCheckParam2.setBusinessLicenseId(businessLicenseId);
        ExecuteResult<List<CusMemberLicenceInfoDTO>> licenceCountResult2 =
                cusMemberLicenceInfoService.selectCusMemberLicenceInfoList(memberLicenceCheckParam2);
        if (!licenceCountResult2.isSuccess()){
            throw new RuntimeException(licenceCountResult2.getErrorMessages().toString());
        }
        if (licenceCountResult2.getResult().size()>0){
            if (memberId!=null){
                List<CusMemberLicenceInfoDTO> list = licenceCountResult2.getResult();
                for (CusMemberLicenceInfoDTO cusMemberLicenceInfoDTO : list){
                    if (!cusMemberLicenceInfoDTO.getMemberId().equals(memberId)){
                        return true;
                    }
                }
            }else{
                return true;
            }
        }
        return false;
    }

    @RequestMapping("/transferLicenceBySecret")
    public String transferLicenceBySecret(){

        String[] ids = "".split(",");

        for (String id : ids){
            Long lid = Long.valueOf(id);
            ExecuteResult<CusMemberLicenceInfoDTO> licenceResult = cusMemberLicenceInfoService.selectCusMemberLicenceInfoById(lid);
            if (licenceResult.getResult()!=null){
                CusMemberLicenceInfoDTO dto = licenceResult.getResult();

                CusMemberLicenceInfoDTO updateParam = new CusMemberLicenceInfoDTO();
                updateParam.setId(lid);
                if (StringUtils.isNotEmpty(dto.getBuyerBusinessLicenseId())){
                    String tmp = secretForDesService.encrypt(dto.getBuyerBusinessLicenseId(),"","");
                    updateParam.setBuyerBusinessLicenseId(tmp);
                }

                if (StringUtils.isNotEmpty(dto.getUnifiedSocialCreditCode())){
                    String tmp = secretForDesService.encrypt(dto.getUnifiedSocialCreditCode(),"","");
                    updateParam.setUnifiedSocialCreditCode(tmp);
                }

                ExecuteResult<Boolean> updateLicence = cusMemberLicenceInfoService.updateCusMemberLicenceInfoById(updateParam);
                if (!updateLicence.isSuccess()){
                    throw new RuntimeException(updateLicence.getErrorMessages().toString());
                }
            }

        }

        return "200";
    }


    private String UAP_PWD = "a123456";
    private String UAP_USERCODE = "weaver";
    private String UAP_DATASOURCE = "ncc_cloud";
    private String UAP_URL = "http://171.16.50.43:80/";

    private String getToken(){
        String uap_token="";
        JSONObject postdata=new JSONObject();
        try {
            postdata.put("pwd", UAP_PWD);
            postdata.put("usercode", UAP_USERCODE);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Map<String, String> header = new HashMap<String, String>();
        header.put("uap_dataSource", UAP_DATASOURCE);
        header.put("uap_usercode", UAP_USERCODE);
        String result = null;
        try {
            result = HttpClientUtil.post(UAP_URL+"uapws/rest/user/login",
                    header, postdata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(result)) {
            try {
                JSONObject resultjson = JSONObject.parseObject(result);
                uap_token = resultjson.getString("uap_token");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return uap_token;
    }

    @RequestMapping("/getFinancialOrg")
    public String getFinancialOrg(){
        Map<String, String> header = new HashMap<String, String>();
        header.put("uap_dataSource",UAP_DATASOURCE);
        header.put("uap_usercode",UAP_USERCODE);
        header.put("uap_token",getToken());
        header.put("Content-Type","application/json");
        Map<String, String> body = new HashMap<String, String>();
        body.put("code","");
        body.put("ts","2000-01-01 00:00:00");
        String res = null;
        try {
            res = HttpClientUtil.httpPost(UAP_URL+"/uapws/rest/orgInfo/queryDataArray",
                    header, JSONObject.toJSONString(body));
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject obj = JSONObject.parseObject(res);
        return obj.toJSONString();
    }

    /**
     * 批量刷证照信息
     * @return
     */
    @RequestMapping("/readLicence")
    public String readLicence(){

        try{
            ExcelData sheet1 = new ExcelData("C:\\Users\\大糊\\Desktop\\202108191824.xlsx", "Sheet1");
            List<MemberBaseInfoDTO> list = sheet1.readLicence();

            for(MemberBaseInfoDTO dto : list){

                CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
                cusMemberBaseInfoDTO.setCompanyCode(dto.getCompanyCode());
                ExecuteResult<CusMemberBaseInfoDTO> memberResult = cusMemberBaseInfoService.selectMemberBaseInfo(cusMemberBaseInfoDTO);
                if (!memberResult.isSuccess()){
                    logger.info("操作失败1：{}",dto.getCompanyCode());
                    continue;
                }
                if (memberResult.getResult()!=null){
                    CusMemberLicenceInfoDTO cusMemberLicenceInfoDTO = new CusMemberLicenceInfoDTO();
                    cusMemberLicenceInfoDTO.setMemberId(memberResult.getResult().getId());
                    cusMemberLicenceInfoDTO.setBuyerBusinessLicenseId(dto.getBuyerBusinessLicenseId());
                    cusMemberLicenceInfoDTO.setBusinessLicenseId(dto.getBuyerBusinessLicenseId());
                    cusMemberLicenceInfoDTO.setUnifiedSocialCreditCode(dto.getBuyerBusinessLicenseId());
                    cusMemberLicenceInfoDTO.setTaxManId(dto.getBuyerBusinessLicenseId());
                    ExecuteResult<Boolean> updateResult = cusMemberLicenceInfoService.updateCusMemberLicenceInfoByMemberId(cusMemberLicenceInfoDTO);
                    if (!updateResult.isSuccess()){
                        logger.info("操作失败2：{}",dto.getCompanyCode());
                        continue;
                    }
                }
                logger.info("操作成功：{}",dto.getCompanyCode());
            }
            return "ok";
        }catch (Exception e){
            return e.getMessage();
        }
    }


    /**
     * 批量刷证照信息
     * @return
     */
    @RequestMapping("/transferLicence")
    public String transferLicence(){
        String[] licenceIds = "".split(",");
        for (String id : licenceIds){
            if (StringUtils.isEmpty(id)){
                System.out.println("解密：");
                continue;
            }
            System.out.println("解密："+secretForDesService.decrypt(id,"",""));
        }
        return "200";
    }


    /**
     * 筛选社统编码为空或不为9开头的
     * @return
     */
    @RequestMapping("/checkUnifCode")
    public String checkUnifCode(){

        String [] codes = "".split(",");
        for (String code : codes){

            CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
            cusMemberBaseInfoDTO.setMemberCode(code);
            cusMemberBaseInfoDTO.setBuyerSellerType("1");
            ExecuteResult<CusMemberBaseInfoDTO> memberResult = cusMemberBaseInfoService.selectMemberBaseInfoLicence(cusMemberBaseInfoDTO);
            CusMemberBaseInfoDTO dto = memberResult.getResult();
            if (dto!=null){
                if (StringUtils.isEmpty(dto.getUnifiedSocialCreditCode())||(!dto.getUnifiedSocialCreditCode().startsWith("9"))){
                    logger.info("异常数据：{},{}",dto.getMemberCode(),dto.getUnifiedSocialCreditCode());
                }
            }
        }
        return "ok";
    }

    @RequestMapping("/batchErpDown")
    public String batchErpDown(){
        String[] ids = "".split(",");
//        String[] ids = "360490".split(",");
        for (String idStr : ids){
            Long id = Long.valueOf(idStr);

            CusMemberStatusInfoDTO cusMemberStatusInfoDTO = new CusMemberStatusInfoDTO();
            cusMemberStatusInfoDTO.setInfoType("5");
            cusMemberStatusInfoDTO.setMemberId(id);
            ExecuteResult<Integer> countResult = cusMemberStatusInfoService.selectCusMemberStatusInfoCount(cusMemberStatusInfoDTO);
            if (countResult.isSuccess()){
                if (countResult.getResult() == 0){
                    CusMemberStatusInfoRegisterDTO cusMemberStatusInfoRegisterDTO = new CusMemberStatusInfoRegisterDTO();
                    cusMemberStatusInfoRegisterDTO.setMemberId(id);
                    cusMemberStatusInfoRegisterDTO.setInfoType("5");
                    cusMemberStatusInfoRegisterDTO.setCreateId(0L);
                    cusMemberStatusInfoRegisterDTO.setCreateName("OA");
                    cusMemberStatusInfoRegisterDTO.setVerifyId(0L);
                    cn.htd.framework.common.ExecuteResult<Boolean> result3 = cusMemberStatusInfoService.insertMemberStatusInfoRegister(cusMemberStatusInfoRegisterDTO);
                    if(!result3.isSuccess()) {
                        throw new RuntimeException(result3.getErrorMessages().toString());
                    }

                    CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
                    cusMemberBaseInfoDTO.setId(id);
                    cusMemberBaseInfoDTO.setModifyTime(new Date());
                    ExecuteResult<Boolean> updateResult = cusMemberBaseInfoService.updateCusMemberBaseInfoById(cusMemberBaseInfoDTO);
                    if(!updateResult.isSuccess()) {
                        throw new RuntimeException(updateResult.getErrorMessages().toString());
                    }

                    logger.info("batchErpDown 处理成功：{}",id);
                }else {
                    logger.info("batchErpDown 已存在记录：{}",id);
                }
            }
        }
        return "200";
    }

    @RequestMapping("/batchUpdateBoxRelationship")
    public String batchUpdateBoxRelationship(){
        String[] ids = "672707,671319,672087,670715,671745,672045,673169,673501".split(",");
        for (String idStr : ids){
            Long id = Long.valueOf(idStr);

            CusBoxRelationshipDTO cusBoxRelationshipDTO = new CusBoxRelationshipDTO();
            cusBoxRelationshipDTO.setBoxId(id);
            cusBoxRelationshipDTO.setErpStatus("1");
            cusBoxRelationshipDTO.setModifyTime(new Date());
            ExecuteResult<Boolean> updateResult = cusBoxRelationshipService.updateCusBoxRelationshipById(cusBoxRelationshipDTO);
            if(!updateResult.isSuccess()) {
                throw new RuntimeException(updateResult.getErrorMessages().toString());
            }
        }
        return "200";
    }

    @RequestMapping("/getInfoByName")
    public String getInfoByName(){
        String[] names = "".split(",");
        for (String name : names){

            CusMemberBaseInfoDTO cusMemberBaseInfoDTO = new CusMemberBaseInfoDTO();
            cusMemberBaseInfoDTO.setCompanyName(name);
            cusMemberBaseInfoDTO.setBuyerSellerType("2");
            ExecuteResult<CusMemberBaseInfoDTO> infoResult = cusMemberBaseInfoService.selectMemberBaseInfoLicence(cusMemberBaseInfoDTO);
            if (infoResult.getResult() == null){
                cusMemberBaseInfoDTO.setBuyerSellerType("1");
                infoResult = cusMemberBaseInfoService.selectMemberBaseInfoLicence(cusMemberBaseInfoDTO);
            }
            if (infoResult.getResult()!=null){
                CusMemberBaseInfoDTO dto = infoResult.getResult();
                logger.info("getInfoByName {},{},{},{},{}",dto.getCompanyName(),dto.getMemberCode(),dto.getCompanyCode(),dto.getSupplierCode(),dto.getUnifiedSocialCreditCode());
            }else {
                logger.info("getInfoByName 不存在:{}",name);
            }

        }
        return "200";
    }
}
